package com.gps.skyrc.activity;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.gps.skyrc.R;
import com.gps.skyrc.activity.base.BaseActivity;
import com.gps.skyrc.api.Config;
import com.gps.skyrc.tool.MyTitleBar;
import com.gps.skyrc.tool.PromptDialog;
import com.gps.skyrc.tool.SharedPreferencesUtils;
import com.gps.skyrc.tool.Tip;
import com.gps.skyrc.tool.logger.ILogger;

import butterknife.BindView;

/**
 * Create by ywq
 * <p>
 * 把英里全转成km发过去
 * data 2018/11/26
 */
public class BeelineModeActivity extends BaseActivity implements View.OnClickListener, View.OnFocusChangeListener {
    @BindView(R.id.beeline_title)
    MyTitleBar beelineTitle;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.speed_ll)
    LinearLayout speedLl;
    @BindView(R.id.distance_ll)
    LinearLayout distanceLl;
    private RelativeLayout mSpeedStartRl;
    private RelativeLayout mSpeedEndRl;
    private RelativeLayout mDistanceStartRl;
    private RelativeLayout mDistanceEndRl;
    private EditText mSpeedStartEdit;
    private TextView mSpeedStartTv;
    private EditText mSpeedEndEdit;
    private TextView mSpeedEndTv;
    private EditText mDistanceStartEdit;
    private TextView mDistanceStartTv;
    private EditText mDistanceEndEdit;
    private TextView mDistanceEndTv;
    private BleDevice mBleDevice;
    private int mode = 3;//3默认  0速度 1距离
    private int mSatellites_num;
    private String mLastMac;
    private int mUnit;

    @Override
    protected void getLayout() {
        setContentView(R.layout.activity_beeline_mode);
    }

    @Override
    protected void setTitleBar() {
        beelineTitle.initViewsVisible(true, true, false, true, false, true);
        beelineTitle.setAppTitle(getString(R.string.beeline_test));
        beelineTitle.setOnLeftButtonClickListener(v -> onBackPressed());
    }

    @Override
    protected void init() {
        mSpeedStartRl = findViewById(R.id.speed_test_start);
        mSpeedEndRl = findViewById(R.id.speed_test_end);
        mDistanceStartRl = findViewById(R.id.distance_test_start);
        mDistanceEndRl = findViewById(R.id.distance_test_end);
        mSpeedStartEdit = mSpeedStartRl.findViewById(R.id.edit);
        mSpeedStartTv = mSpeedStartRl.findViewById(R.id.hint_tv);
        mSpeedEndEdit = mSpeedEndRl.findViewById(R.id.edit);
        mSpeedEndTv = mSpeedEndRl.findViewById(R.id.hint_tv);
        mDistanceStartEdit = mDistanceStartRl.findViewById(R.id.edit);
        mDistanceStartTv = mDistanceStartRl.findViewById(R.id.hint_tv);
        mDistanceEndEdit = mDistanceEndRl.findViewById(R.id.edit);
        mDistanceEndTv = mDistanceEndRl.findViewById(R.id.hint_tv);

        mLastMac = (String) SharedPreferencesUtils.getParam(mContext, SharedPreferencesUtils.PreKey.LAST_DEVICE_MAC, "");
        mUnit = (int) SharedPreferencesUtils.getParam(mContext, mLastMac, 0);//0km  1mi
        mBleDevice = getIntent().getParcelableExtra(Config.BLE_SEND_BLEDEVICE);
        mSatellites_num = getIntent().getIntExtra("satellites_num", 0);
        btn.setBackground(getResources().getDrawable(R.drawable.unready_btn_bg));
        btn.setEnabled(false);
        btn.setOnClickListener(this);

        if (mUnit == 0) {
            mSpeedStartTv.setText(getString(R.string.kmh));
            mSpeedEndTv.setText(getString(R.string.kmh));
            mDistanceStartTv.setText(getString(R.string.m));
            mDistanceEndTv.setText(getString(R.string.m));
        } else {
            mSpeedStartTv.setText(getString(R.string.mih));
            mSpeedEndTv.setText(getString(R.string.mih));
            mDistanceStartTv.setText(getString(R.string.mi));
            mDistanceEndTv.setText(getString(R.string.mi));
        }

        String saveBeforeWrite = (String) SharedPreferencesUtils.getParam(mContext, SharedPreferencesUtils.PreKey.BEELINE_MODE_WRITE_DATA_BEFORE, "");
        assert saveBeforeWrite != null;
        if (!saveBeforeWrite.equals("")) {
            String[] split = saveBeforeWrite.split("-");
            if (split[0].equals("0")) {//速度
                isChooseSpeed(true,false);
                mSpeedStartEdit.setText(split[1]);
                mSpeedEndEdit.setText(split[2]);
            } else if (split[1].equals("1")) {//距离
                isChooseSpeed(false,false);
                mDistanceEndEdit.setText(split[2]);
            }
        }

        mDistanceStartEdit.setText("0");
        mDistanceStartEdit.setFocusable(false);
        mDistanceEndEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});

        speedLl.setOnClickListener(this);
        distanceLl.setOnClickListener(this);
        mSpeedStartEdit.addTextChangedListener(new Watcher(mSpeedStartEdit));
        mSpeedEndEdit.addTextChangedListener(new Watcher(mSpeedEndEdit));
        mDistanceEndEdit.addTextChangedListener(new Watcher(mDistanceEndEdit));
        mSpeedStartEdit.setOnFocusChangeListener(this);
        mSpeedEndEdit.setOnFocusChangeListener(this);
        mDistanceEndEdit.setOnFocusChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btn) {
            if (mSatellites_num >= 4)
                startBeeline();
            else {
                PromptDialog promptDialog = new PromptDialog(mContext, getResources().getString(R.string.satellite_signal_weak));
                promptDialog.show();
                promptDialog.setConfirmClickListener(promptDialog::dismiss);
            }
        } else if (v == speedLl) {
            isChooseSpeed(true,true);
        } else if (v == distanceLl) {
            isChooseSpeed(false,true);
        }
    }

    //发送测试数据
    private void startBeeline() {
        int start = 0;
        int end = 0;
        if (mode == 0) {
            if (mUnit == 1) {//1英里/h = 1.609km/h
                start = (int) (Integer.parseInt(mSpeedStartEdit.getText().toString().trim()) * 1.609);
                end = (int) (Integer.parseInt(mSpeedEndEdit.getText().toString().trim()) * 1.609);
            } else {
                start = Integer.parseInt(mSpeedStartEdit.getText().toString().trim());
                end = Integer.parseInt(mSpeedEndEdit.getText().toString().trim());
            }
        } else if (mode == 1) {
            if (mUnit == 1)//1英里 = 1609m
                end = Integer.parseInt(mDistanceEndEdit.getText().toString().trim()) * 1609;
            else
                end = Integer.parseInt(mDistanceEndEdit.getText().toString().trim());
        }


        byte[] cmd = {0x0f, 0x08, 0x01, 0, (byte) mode, (byte) start, (byte) (end / 256), (byte) (end | 256), 0, 0, (byte) 0xff, (byte) 0xff};
        int checksum = 1;
        for (int i = 2; i < 9; i++)
            checksum += cmd[i];
        cmd[9] = (byte) (checksum & 0xFF);
        BleManager.getInstance().write(mBleDevice, Config.UUID_SERVICE, Config.UUID_WRITE, cmd, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                ILogger.d("success set line mode");
                String save = "";
                if (mode == 0)
                    save = mode + "-" + mSpeedStartEdit.getText().toString().trim() + "-" + mSpeedEndEdit.getText().toString().trim();
                else
                    save = mode + "-" + "0" + "-" + mDistanceEndEdit.getText().toString().trim();
                SharedPreferencesUtils.setParam(mContext, SharedPreferencesUtils.PreKey.BEELINE_MODE_WRITE_DATA_BEFORE, save);
                onBackPressed();
            }

            @Override
            public void onWriteFailure(BleException exception) {
                Tip.showToast(mContext, R.string.send_error);
            }
        });
    }

    private void isChooseSpeed(boolean isSpeed, boolean clean) {
        if (isSpeed) {
            speedLl.setAlpha(1f);
            distanceLl.setAlpha(0.3f);
            if (clean)
                mDistanceEndEdit.setText("");
        } else {
            speedLl.setAlpha(0.3f);
            distanceLl.setAlpha(1f);
            if (clean) {
                mSpeedStartEdit.setText("");
                mSpeedEndEdit.setText("");
            }
        }
    }


    private boolean compare(int start, int end) {
        if (start < end)
            return true;
        else
            return false;
    }

    private void openBtn() {
        btn.setEnabled(true);
        btn.setBackground(getResources().getDrawable(R.drawable.ready_btn_bg));
    }

    private void closeBtn() {
        btn.setEnabled(false);
        btn.setBackground(getResources().getDrawable(R.drawable.unready_btn_bg));
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v == mSpeedStartEdit) {
            if (hasFocus) isChooseSpeed(true,true);
        } else if (v == mSpeedEndEdit) {
            if (hasFocus) isChooseSpeed(true,true);
        } else if (v == mDistanceEndEdit) {
            if (hasFocus) isChooseSpeed(false,true);
        }
    }

    private class Watcher implements TextWatcher {
        private EditText mEditTextId = null;

        public Watcher(EditText id) {
            mEditTextId = id;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            boolean compare = false;
            if (mEditTextId == mSpeedStartEdit) {
                if (mUnit == 0) {
                    if (s.length() > 0 && Integer.parseInt(s.toString()) > 255) {
                        mSpeedStartEdit.setText("255");
                        return;
                    }
                } else if (mUnit == 1) {
                    if (s.length() > 0 && Integer.parseInt(s.toString()) > 158) {
                        mSpeedStartEdit.setText("158");
                        return;
                    }
                }
                if (s.length() > 0 && mSpeedEndEdit.getText().toString().length() > 0) {
                    compare = compare(Integer.parseInt(s.toString()), Integer.parseInt(mSpeedEndEdit.getText().toString()));
                    mode = compare ? 0 : 3;
                }
            } else if (mEditTextId == mSpeedEndEdit) {
                if (mSpeedStartEdit.getText().toString().length() > 0 && s.length() > 0) {
                    compare = compare(Integer.parseInt(mSpeedStartEdit.getText().toString()), Integer.parseInt(s.toString()));
                    mode = compare ? 0 : 3;
                }
            } else if (mEditTextId == mDistanceEndEdit) {
                if (mUnit == 1) {//英里400 = 64000多  限制不然会超出
                    if (s.length() > 0 && Integer.parseInt(s.toString()) > 400) {
                        mDistanceEndEdit.setText("400");
                        return;
                    }
                }
                if (s.toString().length() > 0) {
                    compare = compare(0, Integer.parseInt(s.toString()));
                    mode = compare ? 1 : 3;
                }
            }

            if (compare)
                openBtn();
            else
                closeBtn();
        }
    }
}
